<template>
  <div class="login">
    <router-link to="/">
      <img
        src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1114%2F092H0113055%2F20092G13055-1-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1664762953&t=c229d276b477c235d6dddb0a60495527"
        class="logo"
        alt=""
      />
    </router-link>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userName"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="repassword"
        label="确认密码"
        placeholder="请在次输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
    <router-link :to="{ name: 'Login' }">已有账号，我要登录</router-link>
  </div>
</template>

<script>
import { regAPI } from "../service/auth";
import { setToken } from "../utils/auth";
import { Notify } from "vant";
export default {
  data() {
    return {
      userName: "",
      password: "",
      repassword: "",
    };
  },
  methods: {
    async onSubmit() {
      if (this.password != this.repassword) {
        Notify({
          type: "warning",
          message: "两次密码不一致",
        });
        return;
      }
      // setToken("123");
      const info = await regAPI({
        userName: this.userName,
        password: this.password,
      });
      // console.log(info); // 返回一个对象，有code和data，code表示登录成功，data表示存入的token
      // 返回的数据info自带有code，服务器自带 code 这个数据 code等于1 就表示注册成功
      if (info.code == 1) {
        Notify({
          type: "success",
          message: "注册成功",
        });
        // 注册成功然后存数据
        setToken(info.data); // info 是服务器传过来的
        // dispatch 派发一个action 获取购物车信息
        this.$store.dispatch("loadCarts");
        // 跳转到登录页面
        this.$router.replace({
          name: "Login",
        });
      } else {
        Notify({
          type: "danger",
          message: "注册异常",
        });
      }
    },
  },
};
</script>

<style scoped>
.logo {
  width: 45vw;
  display: block;
  margin: 20px auto;
  border-radius: 16px;
}
</style>
